package com.cxs.biyesheji.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.cxs.biyesheji.config.AlipayConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.UUID;

@Controller
public class AlipayController {

    private final AlipayConfig alipayConfig;

    @Autowired
    public AlipayController(AlipayConfig alipayConfig) {
        this.alipayConfig = alipayConfig;
    }

    @PostMapping(value = "/alipay", produces = "text/html; charset=UTF-8")
    @ResponseBody
    public String pay(@RequestParam("amount") String amount) {
        try {
            // Initialize AlipayClient
            AlipayClient alipayClient = new DefaultAlipayClient(
                    alipayConfig.getGatewayUrl(),
                    alipayConfig.getAppId(),
                    alipayConfig.getPrivateKey(),
                    "json",
                    "UTF-8",
                    alipayConfig.getPublicKey(),
                    "RSA2"
            );

            // Set request parameters
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
            alipayRequest.setReturnUrl(alipayConfig.getReturnUrl());
            alipayRequest.setNotifyUrl(alipayConfig.getNotifyUrl());

            // Generate a unique order number using UUID
            String orderNo = UUID.randomUUID().toString();
            alipayRequest.setBizContent("{\"out_trade_no\":\"" + orderNo + "\","
                    + "\"total_amount\":\"" + amount + "\","
                    + "\"subject\":\"订单支付\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

            // Send the payment request and get the HTML content of the payment page
            String form = alipayClient.pageExecute(alipayRequest).getBody();

            // Return the HTML content of the payment page to the frontend
            return form;
        } catch (AlipayApiException e) {
            System.err.println("Alipay API exception: " + e.getMessage());
            e.printStackTrace();
            // Return error message to the frontend
            return "支付初始化失败，请重试！原因：" + e.getMessage();
        }
    }
}
